package com.itheima.filter;

import com.alibaba.fastjson.JSON;
import com.itheima.bean.User;
import com.itheima.common.R;
import com.itheima.utils.BaseContext;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.language.bm.Rule;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author hebing
 * @version 1.0
 */
//检查用户是否已经完成校验
@WebFilter(filterName = "loginCheckFilter",urlPatterns = "/*")
@Slf4j
public class LoginCheckFilter implements Filter {
    //创建一个匹配器  支持通配符
    public static final AntPathMatcher pathMatcher = new AntPathMatcher();

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        //向下转型
        HttpServletRequest request= (HttpServletRequest) servletRequest;
        HttpServletResponse response= (HttpServletResponse) servletResponse;
        //获取路径
        String uri = request.getRequestURI();
        System.out.println(uri);
        //在配置类打上@ServletComponentScan注解开启扫描过滤器类
        //定义不用过滤的路径
        String[] paths={"/employee/login","/employee/logout","/backend/**","/front/**","/common/**","/user/smscode","/user/login"};
        boolean matchLogin = matchLogin(paths, uri);
        //如果不需要登录 放行
        if(matchLogin){
            log.info("本次请求{}不需要处理",uri);
            filterChain.doFilter(request,response);
            //结束
            return;
        }
        //来到这里 表示需要登录 判断用户是否登录
        if(request.getSession().getAttribute("employee")!=null){
            //说明登录了
            log.info("用户已经登录,用户id为{}",request.getSession().getAttribute("employee"));
            //登录放行之前给线程设置登陆者的id
            Long empId = (Long) request.getSession().getAttribute("employee");
            BaseContext.setCurrentId(empId);
            //放行
            filterChain.doFilter(request,response);
            return;
        }
        //来到这里判断session中user是否有值 有就放行
        User user = (User) request.getSession().getAttribute("user");
        if(user!=null){
            //登录放行之前给线程设置登陆者的id
            BaseContext.setCurrentId(user.getId());
            //直接放行
            filterChain.doFilter(request,response);
            //结束
            return;
        }

        //没有登录 提示登录
        if(uri.contains("backend")){
            response.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));
        }else {
            response.sendRedirect("/front/page/login.html");
        }
    }
    //定义一个方法 判断获取路径是否匹配不需要登录的路径
    public boolean matchLogin(String[] paths,String uri){
        for (String path : paths) {
            boolean match=pathMatcher.match(path,uri);
            if(match){
                return true;
            }
        }
        return false;
    }
}
